<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\response\Json;

//    // 问题反馈列表
//    public function list(Request $request): Json
//    {
//        try {
//            //var_dump(111);die;
//            $param = $request->param();
//            $page = $param['page'] ?? 1;
//            $limit = $param['limit'] ?? 10;
//            $map = [];
//            if ($param['mobile_phone'] ?? "") $map[] = ['mu.mobile_phone', 'like', '%' . $param['mobile_phone'] . '%'];
//            if ($param['type'] ?? "") $map[] = ['fb.type', '=', $param['type']];
//            if ($param['status'] ?? "") $map[] = ['fb.status', '=', $param['status']];
//
//            $dataObj = Db::name('feedback')
//                ->alias('fb')
//                ->leftJoin('member_user mu', 'fb.sender_id = mu.id')
//                ->field(["fb.*", "mu.nickname", "mu.mobile_phone", "(SELECT GROUP_CONCAT(image SEPARATOR '|') FROM member_feedback_image WHERE feedback_id = fb.feedback_id) as images"])
//                ->where($map)
//                ->fetchSql(false)
//                ->order('fb.created_at', 'desc')
//                ->page($page, $limit)
//                ->select();
//            //var_dump($dataObj);die();
//
//            $dataArr = $dataObj->toArray();
//            foreach ($dataArr as $key => $value) {
//                $dataArr[$key]['sender_id'] = strval($value['sender_id']);
//                $dataArr[$key]['feedback_id'] = strval($value['feedback_id']);
//                //处理type和status
//
//               // `type` tinyint(2) NOT NULL DEFAULT '1' COMMENT '问题类型1 => ''商品购买'', 2 => ''账号问题'', 3=> ''游戏闪退'', 4=> ''意见建议'', 5 => ''其他''',
//                if ($value['type'] == 1) {
//                    $dataArr[$key]['type_desc'] = '商品购买';
//                } elseif ($value['type'] == 2) {
//                    $dataArr[$key]['type_desc'] = '账号问题';
//                } elseif ($value['type'] == 3) {
//                    $dataArr[$key]['type_desc'] = '游戏闪退';
//                } elseif ($value['type'] == 4) {
//                    $dataArr[$key]['type_desc'] = '意见建议';
//                } elseif ($value['type'] == 5) {
//                    $dataArr[$key]['type_desc'] = '其他';
//                } elseif ($value['type'] == 6) {
//                    $dataArr[$key]['type_desc'] = '页面展示';
//                }else{
//                    $dataArr[$key]['type_desc'] = '未知类型';
//                }
//                //`status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '问题状态1 => ''未读'', 2 => ''处理中'', 3 => ''已解决'', 4=> ''忽略''
//                if ($value['status'] == 1) {
//                    $dataArr[$key]['status_desc'] = '未读';
//                } elseif ($value['status'] == 2) {
//                    $dataArr[$key]['status_desc'] = '处理中';
//                } elseif ($value['status'] == 3) {
//                    $dataArr[$key]['status_desc'] = '已解决';
//                } elseif ($value['status'] == 4) {
//                    $dataArr[$key]['status_desc'] = '忽略';
//                }else{
//                    $dataArr[$key]['status_desc'] = '未知状态';
//                }
//
//                if ($value['is_reproducible'] == 0) {
//                    $dataArr[$key]['is_reproducible_desc'] = '否';
//                } else {
//                    $dataArr[$key]['is_reproducible_desc'] = '是';
//                }
//                $dataArr[$key]['images'] = !empty($value['images']) ? explode('|', $value['images']) : [];
//                foreach ($dataArr[$key]['images'] as $imageKey => $imageValue) {
//                    $dataArr[$key]['images'][$imageKey] = config('basic.cdn') . $imageValue;
//                }
//            }
//            $count = Db::name('feedback')->alias('fb')
//                ->leftJoin('member_user mu', 'fb.sender_id = mu.id')
//                ->fetchSql(false)
//                ->where($map)
//                ->count();
//            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $dataArr, 'count' => $count]]);
//        } catch (\Exception $e) {
//            return json(['code' => -1, 'msg' => '获取用户游戏库失败：' . $e->getMessage()]);
//        }
//    }
//
//    // 修改问题描述和问题状态
//    public function edit(Request $request): Json
//    {
//        try {
//            $param = $request->param();
//            $feedback = Db::name('feedback')->where('feedback_id', $param['feedback_id'] ?? '')->find();
//            if (!$feedback) {
//                return json(['code' => -1, 'msg' => '反馈不存在']);
//            }
//            if ($param['description'] ?? "") {
//                $line['description'] = $param['description'];
//            }
//            if ($param['status'] ?? "") {
//                $line['status'] = $param['status'];
//            }
//            $line['updated_at'] = date('Y-m-d H:i:s');
//            Db::name('feedback')->where('feedback_id', $param['feedback_id'] ?? '')->fetchSql(false)->update($line);
//            return json(['code' => 0, 'msg' => '修改成功']);
//        } catch (\Exception $e) {
//            return json(['code' => -1, 'msg' => '修改失败：' . $e->getMessage()]);
//        }
//
//    }

//
//CREATE TABLE `carousel` (
//`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键 ID',
//`carousel_id` bigint(18) NOT NULL COMMENT '轮播图 ID，使用雪花算法生成',
//`title` varchar(255) NOT NULL COMMENT '标题',
//`tags` json NOT NULL COMMENT '标签，使用 JSON 数组存储',
//`cover_image` varchar(255) NOT NULL COMMENT '封面图 URL',
//`type` tinyint(1) NOT NULL COMMENT '类型，0: 图片，1: 视频',
//`file_url` varchar(255) NOT NULL COMMENT '文件 URL',
//`click_action` tinyint(1) NOT NULL COMMENT '点击动作，0: 跳转，1: 下载',
//`jump_url` varchar(255) DEFAULT NULL,
//`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
//`is_display` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否展示，0: 不展示，1: 展示',
//`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
//`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
//PRIMARY KEY (`id`) USING BTREE,
//UNIQUE KEY `carousel_id` (`carousel_id`) USING BTREE,
//KEY `idx_carousel_id` (`carousel_id`) USING BTREE,
//KEY `idx_title` (`title`) USING BTREE,
//KEY `idx_type` (`type`) USING BTREE,
//KEY `idx_is_display` (`is_display`) USING BTREE
//) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='官网轮播图表';
//
//12	569708190107832320	军团要塞2	["动作,Steam 集换式卡牌,免费开玩"]	/home-page/440_header.jpg	0	/home-page/440-movie480.mp4	1	/platform/mysteam%20Setup%201.3.5.exe	0	1	2025-04-22 10:16:57	2025-05-14 09:07:02
//13	569709608009076736	石油骚动	["独立,模拟,策略"]	/home-page/361280_header.jpg	0	/home-page/361280-movie480.mp4	1	/platform/mysteam%20Setup%201.3.5.exe	1	1	2025-04-22 10:22:35	2025-05-14 09:07:02
//14	569710036474007552	灵魂旅人	["冒险,独立,模拟"]	/home-page/972660_header.jpg	0	/home-page/972660-movie480.mp4	1	/platform/mysteam%20Setup%201.3.5.exe	2	1	2025-04-22 10:24:17	2025-05-14 09:07:02
//15	569710386648059904	幻兽帕鲁	["动作,冒险,独立,角色扮演,抢先体验"]	/home-page/1623730_header.jpg	0	/home-page/1623730-movie480.mp4	1	/platform/mysteam%20Setup%201.3.5.exe	3	1	2025-04-22 10:25:41	2025-05-14 09:07:02
//16	569711517377892352	隐身英雄	["动作,休闲,独立,策略"]	/home-page/375750_header.jpg	0	/home-page/375750_movie480.mp4	1	/platform/mysteam%20Setup%201.3.5.exe	4	1	2025-04-22 10:30:10	2025-05-14 09:07:02

class Carousel extends BaseController
{
    /**
     * 轮播图列表
     * 
     * @param Request $request
     * @return Json
     */
    public function list(Request $request): Json
    {
        try {
            $param = $request->param();
            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;
            
            $map = [];
            
            // 搜索条件
            if ($param['carousel_id'] ?? "") {
                $map[] = ['carousel_id', '=', $param['carousel_id']];
            }
            
            if ($param['title'] ?? "") {
                $map[] = ['title', 'like', '%' . $param['title'] . '%'];
            }
            
            if ($param['type'] ?? "") {
                $map[] = ['type', '=', $param['type']];
            }
            
            if (isset($param['is_display']) && $param['is_display'] !== "") {
                $map[] = ['is_display', '=', $param['is_display']];
            }
            // 查询数据
            $dataObj = Db::name('carousel')
                ->where($map)
                ->order('sort', 'asc')
                ->order('updated_at', 'desc')
                ->fetchSql(false)
                ->page($page, $limit)
                ->select();
            //var_dump($dataObj);die();

            $dataArr = $dataObj->toArray();

            // 处理数据
            foreach ($dataArr as $key => $value) {
                $dataArr[$key]['carousel_id'] = strval($value['carousel_id']);
                $dataArr[$key]['id'] = strval($value['id']);
                
                // 处理类型描述
                if ($value['type'] == 0) {
                    $dataArr[$key]['type_desc'] = '图片';
                } elseif ($value['type'] == 1) {
                    $dataArr[$key]['type_desc'] = '视频';
                } else {
                    $dataArr[$key]['type_desc'] = '未知类型';
                }
                
                // 处理状态描述
                if ($value['is_display'] == 0) {
                    $dataArr[$key]['display_desc'] = '隐藏';
                } elseif ($value['is_display'] == 1) {
                    $dataArr[$key]['display_desc'] = '显示';
                } else {
                    $dataArr[$key]['display_desc'] = '未知状态';
                }
                
                // 处理标签
                $dataArr[$key]['tags'] = json_decode($value['tags'], true) ?: [];

                // 处理click_action
                if ($value['click_action'] == 0) {
                    $dataArr[$key]['click_action_desc'] = '跳转';
                } elseif ($value['click_action'] == 1) {
                    $dataArr[$key]['click_action_desc'] = '下载';
                } else {
                    $dataArr[$key]['click_action_desc'] = '未知动作';
                }

                // 处理cover_image
                if (!empty($value['cover_image'])) {
                    $dataArr[$key]['cover_image'] = config('basic.cdn') . $value['cover_image'];
                } else {
                    $dataArr[$key]['cover_image'] = '';
                }

                // 处理file_url
                if (!empty($value['file_url'])) {
                    $dataArr[$key]['file_url'] = config('basic.cdn') . $value['file_url'];
                } else {
                    $dataArr[$key]['file_url'] = '';
                }

                // 处理jump_url
                if (!empty($value['jump_url'])) {
                    $dataArr[$key]['jump_url'] = config('basic.cdn') . $value['jump_url'];
                } else {
                    $dataArr[$key]['jump_url'] = '';
                }
            }
            
            // 查询总数
            $count = Db::name('carousel')->where($map)->count();
                
            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $dataArr, 'count' => $count]]);
            
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '获取轮播图列表失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 创建轮播图
     * 
     * @param Request $request
     * @return Json
     */
    public function create(Request $request): Json
    {
        try {
            $param = $request->param();
            
            // 验证必要参数
            if (empty($param['title'])) {
                return json(['code' => -1, 'msg' => '轮播图标题不能为空']);
            }
            
            if (!isset($param['type'])) {
                return json(['code' => -1, 'msg' => '轮播图类型不能为空']);
            }
            
            if (empty($param['cover_image'])) {
                return json(['code' => -1, 'msg' => '封面图不能为空']);
            }
            
            if (empty($param['file_url'])) {
                return json(['code' => -1, 'msg' => '文件URL不能为空']);
            }
            
            if (!isset($param['click_action'])) {
                return json(['code' => -1, 'msg' => '点击动作不能为空']);
            }
            
            // 准备数据
            $snowflake = new \app\common\Snowflake(1, 1);
            $carouselId = $snowflake->generateID();
            
            $data = [
                'carousel_id' => $carouselId,
                'title' => $param['title'],
                'tags' => json_encode($param['tags'] ?? []),
                'cover_image' => $param['cover_image'],
                'type' => intval($param['type']),
                'file_url' => $param['file_url'],
                'click_action' => intval($param['click_action']),
                'jump_url' => $param['jump_url'] ?? '',
                'sort' => $param['sort'] ?? 0,
                'is_display' => $param['is_display'] ?? 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            
            // 插入数据
            $id = Db::name('carousel')->insertGetId($data);
            
            if (!$id) {
                return json(['code' => -1, 'msg' => '创建轮播图失败']);
            }
            
            return json(['code' => 0, 'msg' => '创建成功', 'data' => ['id' => strval($id), 'carousel_id' => strval($carouselId)]]);
            
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '创建轮播图失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新轮播图
     * 
     * @param Request $request
     * @param int $id
     * @return Json
     */
    public function update(Request $request, $id): Json
    {
        try {
            $param = $request->param();
            
            // 检查轮播图是否存在
            $carousel = Db::name('carousel')->where('id', $id)->find();
            if (!$carousel) {
                return json(['code' => -1, 'msg' => '轮播图不存在']);
            }
            
            // 准备更新数据
            $data = [];
            
            if (isset($param['title'])) {
                $data['title'] = $param['title'];
            }
            
            if (isset($param['tags'])) {
                $data['tags'] = json_encode($param['tags']);
            }
            
            if (isset($param['cover_image'])) {
                $data['cover_image'] = $param['cover_image'];
            }
            
            if (isset($param['type'])) {
                $data['type'] = intval($param['type']);
            }
            
            if (isset($param['file_url'])) {
                $data['file_url'] = $param['file_url'];
            }
            
            if (isset($param['click_action'])) {
                $data['click_action'] = intval($param['click_action']);
            }
            
            if (isset($param['jump_url'])) {
                $data['jump_url'] = $param['jump_url'];
            }
            
            if (isset($param['sort'])) {
                $data['sort'] = intval($param['sort']);
            }
            
            if (isset($param['is_display'])) {
                $data['is_display'] = intval($param['is_display']);
            }
            
            $data['updated_at'] = date('Y-m-d H:i:s');
            
            // 更新数据
            $result = Db::name('carousel')->where('id', $id)->update($data);
            
            if ($result === false) {
                return json(['code' => -1, 'msg' => '更新轮播图失败']);
            }
            
            return json(['code' => 0, 'msg' => '更新成功']);
            
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '更新轮播图失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除轮播图
     * 
     * @param Request $request
     * @param int $id
     * @return Json
     */
    public function delete(Request $request, $id): Json
    {
        try {
            // 检查轮播图是否存在
            $carousel = Db::name('carousel')->where('id', $id)->find();
            if (!$carousel) {
                return json(['code' => -1, 'msg' => '轮播图不存在']);
            }
            
            // 删除轮播图
            $result = Db::name('carousel')->where('id', $id)->delete();
            
            if (!$result) {
                return json(['code' => -1, 'msg' => '删除轮播图失败']);
            }
            
            return json(['code' => 0, 'msg' => '删除成功']);
            
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '删除轮播图失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 导出轮播图
     * 
     * @param Request $request
     * @return Json
     */
    public function export(Request $request): Json
    {
        try {
            $param = $request->param();
            
            $map = [];
            
            // 搜索条件
            if ($param['carousel_id'] ?? "") {
                $map[] = ['carousel_id', '=', $param['carousel_id']];
            }
            
            if ($param['title'] ?? "") {
                $map[] = ['title', 'like', '%' . $param['title'] . '%'];
            }
            
            if ($param['type'] ?? "") {
                $map[] = ['type', '=', $param['type']];
            }
            
            if (isset($param['is_display']) && $param['is_display'] !== "") {
                $map[] = ['is_display', '=', $param['is_display']];
            }
            
            // 查询数据
            $dataObj = Db::name('carousel')
                ->where($map)
                ->order('sort', 'asc')
                ->order('updated_at', 'desc')
                ->select();
                
            $dataArr = $dataObj->toArray();
            
            // 处理数据
            foreach ($dataArr as $key => $value) {
                $dataArr[$key]['carousel_id'] = strval($value['carousel_id']);
                $dataArr[$key]['id'] = strval($value['id']);
                
                // 处理类型描述
                if ($value['type'] == 0) {
                    $dataArr[$key]['type_desc'] = '图片';
                } elseif ($value['type'] == 1) {
                    $dataArr[$key]['type_desc'] = '视频';
                } else {
                    $dataArr[$key]['type_desc'] = '未知类型';
                }
                
                // 处理状态描述
                if ($value['is_display'] == 0) {
                    $dataArr[$key]['display_desc'] = '隐藏';
                } elseif ($value['is_display'] == 1) {
                    $dataArr[$key]['display_desc'] = '显示';
                } else {
                    $dataArr[$key]['display_desc'] = '未知状态';
                }
                
                // 处理标签
                $dataArr[$key]['tags'] = json_decode($value['tags'], true) ?: [];
            }
            
            return json(['code' => 0, 'msg' => 'success', 'data' => $dataArr]);
            
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '导出轮播图失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新展示状态
     * 
     * @param Request $request
     * @return Json
     */
    public function updateDisplayStatus(Request $request): Json
    {
        try {
            $param = $request->param();
            
            if (empty($param['id'])) {
                return json(['code' => -1, 'msg' => '轮播图ID不能为空']);
            }
            
            if (!isset($param['is_display'])) {
                return json(['code' => -1, 'msg' => '展示状态不能为空']);
            }
            
            // 检查轮播图是否存在
            $carousel = Db::name('carousel')->where('id', $param['id'])->find();
            if (!$carousel) {
                return json(['code' => -1, 'msg' => '轮播图不存在']);
            }
            
            // 更新状态
            $result = Db::name('carousel')->where('id', $param['id'])->update([
                'is_display' => intval($param['is_display']),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            
            if ($result === false) {
                return json(['code' => -1, 'msg' => '更新展示状态失败']);
            }
            
            return json(['code' => 0, 'msg' => '更新展示状态成功']);
            
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '更新展示状态失败：' . $e->getMessage()]);
        }
    }
}